/*
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-03-02 09:54:42
 * @LastEditTime: 2024-02-04 18:08:14
 */
import fs from 'node:fs'
import path from 'node:path'
import type { LogLevel } from 'vite'
import { defineConfig, loadEnv } from 'vite'
import pkg from './package.json'
export default async ({ mode, command }) => {
  // !框架维护开发一定不要开启，否则会导致代码丢失
  // global + MainApp目录
  // (await import('./src/copy-dir')).copyMain();
  // assets + locales目录
  // (await import('./src/copy-dir')).copyAssets()

  // 动态导入 防止在替换目录前导入时文件不存在
  const logger = (await import('./src/global/plugins/logger')).default
  const createVitePlugins = await (await import('./src/global/plugins')).default

  const folderPath = path.join(__dirname, 'dist')
  if (fs.existsSync(folderPath))
    fs.rmSync(folderPath, { recursive: true })
  const env = loadEnv(mode, './env')
  // 全局 scss 资源
  const scssResources: string[] = []
  fs.readdirSync('src/assets/styles/resources').forEach(dirname => {
    if (fs.statSync(`src/assets/styles/resources/${dirname}`).isFile())
      scssResources.push(`@use "src/assets/styles/resources/${dirname}" as *;`)
  })

  return defineConfig({
    base: './',
    envDir: './env',
    server: {
      host: true,
      open: false,
      port: 9000,
      hmr: {
        overlay: false
      },
      proxy: {
        '/api': {
          target: env.VITE_APP_PROXY_URL,
          changeOrigin: command === 'serve' && env.VITE_OPEN_PROXY === 'true',
          rewrite: path => path.replace(/^\/api/, '')
        },
        '/ws': {
          target: env.VITE_APP_SSOCKET_PROXY_URL,
          changeOrigin: command === 'serve' && env.VITE_OPEN_PROXY === 'true',
          rewrite: path => path.replace(/^\/ws/, '')
        },
        '/jmreport': {
          target: 'http://localhost:8080',
          changeOrigin: true
        }
      },
      // hmr: false,
      warmup: ['./src/global/**/*.vue', './src/MainApp/**/*.vue']
    },
    customLogger: logger,
    build: {
      target: ['es2020', 'edge88', 'firefox78', 'chrome87', 'safari14'],
      outDir: mode === 'production' ? 'dist' : `dist-${mode}`,
      assetsDir: './',
      // cssMinify: 'lightningcss',
      // 启用/禁用 CSS 代码拆分
      cssCodeSplit: true,
      // 启用/禁用 gzip 压缩大小报告;压缩大型输出文件可能会很慢，禁用该功能会提高项目的构建性能
      reportCompressedSize: false,
      chunkSizeWarningLimit: 1000,
      sourcemap: env.VITE_BUILD_SOURCEMAP === 'true',
      rollupOptions: {
        output: {
          chunkFileNames: 'ik-[name]-[hash].js',
          // intro: '/* eslint-disable no-eval */',
          manualChunks: {
            'monaco-editor': ['monaco-editor'],
            tinymce: ['tinymce'],
            'element-plus': ['element-plus'],
            'iking-form': ['iking-form']
          }
        },
        onLog: (level: LogLevel, log: RollupLog) => {
        },
        onWarn: (warning: RollupWarning) => {
          console.info('warning: ', warning)
        }
      }
    },
    define: {
      __SYSTEM_INFO__: JSON.stringify({
        pkg: {
          dependencies: pkg.dependencies,
          devDependencies: pkg.devDependencies
        },
        version: env.VITE_BUILD_VERSION,
        downloadUrl: env.VITE_APP_DOWNLOAD_URL,
        lastBuildTime: new Date().toLocaleString()
      })
    },
    optimizeDeps: {
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: scssResources.join('')
        }
      }
    },
    plugins: createVitePlugins(env, command === 'build'),
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
        '#': path.resolve(__dirname, 'src/types'),
        // type  interface
        '@t': path.resolve(__dirname, 'types'),
        // global
        '@g': path.resolve(__dirname, 'src/global'),
        // enum
        '@e': path.resolve(__dirname, 'src/global/enums'),
        // api
        '@api': path.resolve(__dirname, 'src/global/api'),
        // MainApp
        '@main': path.resolve(__dirname, 'src/MainApp'),
        // MainApp
        '@micro': path.resolve(__dirname, 'src/MicroApp')
      }
    }
  })
}
